<template>
  <view class="user-edit-page">
    <!-- 头像修改区域 -->
    <view class="avatar-section">
      <text class="section-title">头像</text>
      <button class="avatar-btn" open-type="chooseAvatar" @chooseavatar="handleChooseAvatar">
        <image class="avatar-img" :src="avatarUrl" mode="aspectFill" />
      </button>
      <text class="tip-text">点击头像修改（支持JPG/PNG）</text>
    </view>

    <!-- 昵称修改区域 -->
    <view class="nickname-section">
      <text class="section-title">昵称</text>
      <nut-input v-model="nickname" type="nickname" placeholder="请输入昵称" border @change="handleNicknameChange"
        :max-length="20" class="nickname-input" />
      <text class="tip-text">支持特殊符号和emoji表情</text>
    </view>

    <!-- 提交按钮 -->
    <nut-button type="primary" block class="submit-btn" @click="handleSubmit" :disabled="!isFormChanged">
      保存修改
    </nut-button>

    <!-- 头像预览弹窗 -->
    <nut-popup position="center" v-model:visible="showAvatarPreview" round>
      <image :src="tempAvatar" mode="aspectFit" class="avatar-preview" />
      <nut-button type="primary" @click="uploadAvatar" class="confirm-btn">
        确认使用
      </nut-button>
    </nut-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import Taro from '@tarojs/taro'
import { showToast, showLoading, hideLoading } from '@tarojs/taro'
import { store } from '@/store/index'
import http from '@/utils/http';

// 用户状态管理
const { info } = store.storeState;
const defaultAvatar = 'https://static.xxxx.com/default-avatar.png' // 默认头像

// 响应式数据
const avatarUrl = ref(info.value.avatar_url || defaultAvatar)
const nickname = ref(info.value.name || '')
const tempAvatar = ref('') // 临时头像路径
const showAvatarPreview = ref(false)
const originalAvatar = ref(avatarUrl.value)
const originalNickname = ref(nickname.value)

Taro.setNavigationBarTitle({
  title: "用户信息",
});


// 计算表单是否修改
const isFormChanged = computed(() => {
  return avatarUrl.value !== originalAvatar.value || nickname.value !== originalNickname.value
})

// 选择头像回调（微信官方规范）
const handleChooseAvatar = async (e: any) => {
  // const { avatarUrl: tempPath } = e.detail
  // tempAvatar.value = tempPath
  console.log("e.detail", e.detail)

  // showAvatarPreview.value = true
  const res = await http.upload(e.detail.avatarUrl);
  console.log("res &&&", res)
  avatarUrl.value = res
}

// 上传头像到服务器
const uploadAvatar = async () => {
  showLoading({ title: '上传中...' })

  try {
    const res = await Taro.uploadFile({
      url: 'https://api.yourserver.com/upload/avatar',
      filePath: tempAvatar.value,
      name: 'avatar',
      // header: { 'Authorization': `Bearer ${userStore.token}` }
    })

    const data = JSON.parse(res.data)
    if (data.code === 200) {
      avatarUrl.value = data.data.url
      showToast({ title: '头像上传成功', icon: 'success' })
    } else {
      throw new Error(data.message || '上传失败')
    }
  } catch (err) {
    showToast({ title: err.message || '网络错误', icon: 'error' })
  } finally {
    hideLoading()
    showAvatarPreview.value = false
  }
}

// 昵称变更处理（兼容真机BUG）
const handleNicknameChange = (e) => {
  nickname.value = e.detail.value.trim().slice(0, 20)
}

// 提交修改
const handleSubmit = async () => {
  if (!validateForm()) return

  showLoading({ title: '保存中...' })
  http.postQuery("/api/user/update", {
    name: nickname.value,
    avatarUrl: avatarUrl.value
  }).then((res) => {
    console.log("res", res);
    if (res.code == 0) {
      showToast({ title: "保存成功", icon: "success" });
      Taro.navigateBack();
    }
  })
}

// 表单验证
const validateForm = (): boolean => {
  if (!nickname.value) {
    showToast({ title: '昵称不能为空', icon: 'none' })
    return false
  }

  if (nickname.value.length < 2) {
    showToast({ title: '昵称至少2个字符', icon: 'none' })
    return false
  }

  return true
}
</script>

<style lang="scss">
/* 750rpx设计稿基准 */
$design-width: 750rpx;

.user-edit-page {
  padding: 40rpx;
  background-color: #f8f9fb;
  min-height: 100vh;
  box-sizing: border-box;
}

.section-title {
  display: block;
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 30rpx;
}

.avatar-section {
  background: #fff;
  border-radius: 24rpx;
  padding: 40rpx;
  margin-bottom: 40rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.03);

  .avatar-btn {
    padding: 0;
    background: transparent;
    border: none;
    line-height: 1;

    &::after {
      border: none;
    }
  }
}

.nickname-section {
  background: #fff;
  border-radius: 24rpx;
  padding: 40rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.03);

  .nut-input {
    margin: 20rpx 0 !important;
    padding: 0 !important;
  }

  .nickname-input {
    border-radius: 16rpx;
    overflow: hidden;
    width: 100%;
    display: flex;
    border: 2rpx solid #eee;
    padding: 0 20rpx;
    height: 100rpx;
    font-size: 32rpx;
  }
}

.tip-text {
  display: block;
  font-size: 26rpx;
  color: #999;
  margin-top: 20rpx;
}

.submit-btn {
  margin-top: 80rpx;
  height: 96rpx;
  border-radius: 48rpx;
  font-size: 34rpx;
  // background: linear-gradient(90deg, #ff5e3a, #ff2a6a);
  border: none;

  &:disabled {
    opacity: 0.6;
  }
}

.avatar-preview {
  width: 80vw;
  height: 80vw;
  max-width: 600rpx;
  max-height: 600rpx;
}

.confirm-btn {
  margin-top: 40rpx;
  width: 100%;
  border-radius: 48rpx;
  height: 88rpx;
}

.avatar-img {
  width: 160rpx;
  height: 160rpx;
  border-radius: 50%;
  background: #999;
}

/* 响应式适配 */
@media (min-width: 600rpx) {
  .user-edit-page {
    padding: 60rpx;
  }
}
</style>
